package com.spring.pay.cmb.util;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jdom.JDOMException;

import com.spring.pay.cmb.config.CmbConfig;
import com.spring.pay.weixin.util.XMLUtil;
import com.spring.trade.po.TradeOrderInfo;
import com.spring.util.DateUtils;
import com.spring.util.TradeOrderInfoStatus;

public class CmbHttpClient {
	
	public String sendPost(String strurl, String sendcontent) {
		String message = "";
		try {
			URL url = new URL(strurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestProperty("Content-type", "application/xml; encoding=utf-8"); 
		      
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			
			InputStream in = conn.getInputStream();
			int size = in.available();
			byte[] recvBytes = new byte[size];
			in.read(recvBytes);
			in.close();
			if (conn != null) {
				// 关闭连接
				conn.disconnect();
			}
			message = new String(recvBytes, "UTF-8");
			System.out.println(message);
			return message;
		}
		catch (IOException e) {
			e.printStackTrace();
			message = e.getMessage();
			return message;
		}
		catch (Exception e) {
			e.printStackTrace();
			message = e.getMessage();
			return message;
		}
		finally {

		}
	}
	
	public String Encrypt(String strSrc, String encName) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = this.bytes2Hex(md.digest()); // to HexString
		}
		catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	public long dateToMs(String dateTime) {
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dm = null;
		try {
			dm = sdf.parse(dateTime);
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
		return Long.valueOf(dm.getTime());
	}

	public static long getCurrentMs() {
		Date dateTime = new Date();
		return Long.valueOf(dateTime.getTime());
	}
	
	public static void main(String arg[]) {
		/*YwtzfHttpRequest hr = new YwtzfHttpRequest();*/
		CmbHttpClient hr = new CmbHttpClient();
		//单笔订单查询

		
		boolean flag=hr.getTest(0l);
		
		System.out.println(flag);
		
/*		System.out.println("开始");
		for(int i =1; i < 400; i ++){
			System.out.println("i is "  + i);
			long time = 4 * 60 * 1000 * i;
			boolean flag=hr.getTest(time);
			if(flag){
				System.out.println("退款成功; i is " + i);
			}
			System.out.println("==============================");
			
		}*/
		System.out.println("结束");
		
//		String retus  = 	hr.sendPost(CmbConfig.REFUND_URL  + "?Request=" + getBodyes(), "");
//		System.out.println("retus is " + retus);
		
	}
	
	public static String getBodyes(){
		StringBuffer buff = new StringBuffer();

		buff.append("<Request><Head><BranchNo>0571</BranchNo><MerchantNo>001191</MerchantNo>");
		buff.append("<Operator>9999</Operator>");
		buff.append("<Password>001191</Password><TimeStamp>523040465000</TimeStamp>");
		buff.append("<Command>Refund_No_Dup</Command></Head><Body><Date>20160726</Date>");
		buff.append("<BillNo>0347087611</BillNo><RefundNo>P0133030316071215444</RefundNo>");
		buff.append("<Amount>10.00</Amount><Desc>refund</Desc></Body>");
		buff.append("<Hash>c979488e472e36afe2ed264bec4ca2eb0645ad9e</Hash></Request>");
		return buff.toString();
		
		
	}
	
	public  boolean getTest(long times){
		//退款
		long timestamp2 = getCurrentMs() - dateToMs("2000-01-01 00:00:00");
		timestamp2 = timestamp2  + times;
//		timestamp2 = 530885308874l;
		System.out.println("timestamp2 is " + timestamp2);
		
		StringBuffer head2 = new StringBuffer();
		head2.append("<BranchNo>0010</BranchNo>");
		head2.append("<MerchantNo>000253</MerchantNo>");
		head2.append("<Operator>9999</Operator>");
		head2.append("<Password>123456</Password>");
		head2.append("<TimeStamp>" + timestamp2 + "</TimeStamp>");
		head2.append("<Command>Refund_No_Dup</Command>");

//		System.out.println(head2.toString());
		
		StringBuffer body2 = new StringBuffer();
		body2.append("<Date>20161027</Date>");
		body2.append("<BillNo>2621304972</BillNo>");
		body2.append("<RefundNo>NP7idBGChuG5tt1</RefundNo>");
		body2.append("<Amount>1.00</Amount>");
		body2.append("<Desc>111</Desc>");
		
		
		

		StringBuffer sb2 = new StringBuffer();
		sb2.append("<Request><Head>");
		sb2.append(head2);
		sb2.append("</Head><Body>");
		sb2.append(body2);
		sb2.append("</Body><Hash>");
		sb2.append(Encrypt(CmbConfig.SECRET_KEY + head2.toString() + body2.toString(), "SHA-1"));
		sb2.append("</Hash></Request>");
		
//		System.out.println(sb2.toString());
		String msg = sendPost(CmbConfig.REFUND_URL + "?Request=" + sb2.toString(), "");
		
		Map map;
		boolean flag = false;
		try {
			map = XMLUtil.doXMLParse(msg);
			StringBuffer buff = new StringBuffer("<xml>");
			buff.append((String)map.get("Head"));
			buff.append("</xml>");
			map = XMLUtil.doXMLParse(buff.toString());
					
			String resCode = (String)map.get("Code");
			if(StringUtils.isEmpty(resCode)){
				System.out.println("退款成功");
				flag =  true;
			}else{
				flag = false;
			}
		} catch (JDOMException e) {
			e.printStackTrace();
			flag = false;
		} catch (IOException e) {
			e.printStackTrace();
			flag = false;
		}finally {
			return flag;
		}
	
		
	}

}
